import datetime
import os

from django.http import HttpResponse, JsonResponse, HttpResponseNotFound, StreamingHttpResponse, FileResponse
from django.shortcuts import render, redirect
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView

from Hello.forms import StudentForm
from Hello.models import StudentInfo


# Create your views here.
# 定义人类
class Person:
    # 姓名
    name = None
    # 年龄
    age = None

    def __init__(self, name, age):
        self.name = name
        self.age = age


def index(request):
    # 字符串
    str = "qinshanshan"
    # 时间
    date = datetime.datetime.now()
    # 字典
    myDict = {"tom": "666", "cat": "999", "wzw": "333"}
    # 列表
    myList = ["java", "python", "c"]
    # 元组
    myTuple = ("python", 222, 3.14, False)
    # 对象
    zhangsan = Person("张三",21)
    content_value = {"msg": str, "msg2": myDict, "msg3": myList, "msg4": myTuple, "msg5": zhangsan,"date": date}
    return render(request, 'index.html', context=content_value)


def blog(request, id, year, month, day):
    if id == 0:
        return redirect("/static/error.html")
    else:
        return HttpResponse("id是" + str(id) + '/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + "的博客页面")


# 正则路由
def blogs(request, year, month, day):
    return HttpResponse(str(year) + '/' + str(month) + '/' + str(day) + '的博客页面')


# 定义文件路径
file_path = "E:\\Test.txt"


def download_file1(request):
    # 打开文件
    file = open(file_path, 'rb')
    # 创建HttpResponse对象
    response = HttpResponse(file)
    response['Content_Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename=file1.txt'
    return response


def download_file2(request):
    # 打开文件
    file = open(file_path, 'rb')
    # 创建StreamingHttpResponse对象
    response = StreamingHttpResponse(file)
    response['Content_Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename=file2.txt'
    return response


def download_file3(request):
    # 打开文件
    file = open(file_path, 'rb')
    # 创建FileResponse对象
    response = FileResponse(file)
    response['Content_Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename=file3.txt'
    return response


def get_test(request):
    # 请求方式
    print(request.method)  # GET
    # 常用属性
    print(request.content_type)  # text/plain
    print(request.content_params)  # {}
    print(request.COOKIES)
    print(request.scheme)  # http
    # 常用方法
    print(request.is_secure())  # False
    print(request.get_host())  # localhost:8000
    print(request.get_full_path())  # /get?name=qinshanshan&age=23
    print(request.GET.get("name"))  # qinshanshan
    print(request.GET.get("age"))  # 23
    print(request.GET.get("aaa", "666"))  # 获取key为aaa的value,假如没获取到,则默认获取到666
    return HttpResponse("http get ok")


def post_test(request):
    # 请求方式
    print(request.method)  # POST
    # 常用方法
    print(request.POST.get("name"))  # 张三
    print(request.POST.get("age"))  # 21
    print(request.POST.get("aaa", "666"))  # 666
    return HttpResponse("http post ok")


# 登录跳转页面
def to_login(request):
    return render(request, 'login.html')


# 登录逻辑
def login(request):
    userName = request.POST.get("userName")
    password = request.POST.get("password")
    if userName == 'qinshanshan' and password == '123456':
        # 设置session: session中存一个key为currentUserName，value为userName
        request.session['currentUserName'] = userName
        # 获取session
        print("session获取", request.session['currentUserName'])
        # 跳转到主页面
        response = render(request, 'main.html')
        # 设置cookie
        response.set_cookie("remember_me", True)
        return response
    else:
        return render(request, 'login.html')


# 跳转文件上传页面
def to_upload(request):
    return render(request, 'upload.html')


# 文件上传逻辑
def upload(request):
    # 获取上传的文件，如果没有文件，就默认为None
    myFile = request.FILES.get("myfile", None)
    if myFile:
        # 打开特定的文件进行二进制的写操作
        f = open(os.path.join("D:\\myFile", myFile.name), "wb+")
        # 分块写入文件
        for chunk in myFile.chunks():
            f.write(chunk)
        f.close()
        return HttpResponse("文件上传成功!")
    else:
        return HttpResponse("没发现文件！")


# List类
class List(ListView):
    # 设置模板文件
    template_name = 'student/list.html'
    # 设置模型外的数据
    extra_context = {'title': '学生信息列表'}
    # 查询结果集(返回所有的数据库表的数据)
    queryset = StudentInfo.objects.all()
    # 每页展示10条数据
    paginate_by = 10
    # 设置上下文对象名称
    context_object_name = 'student_list'


class Detail(DetailView):
    # 设置模板文件
    template_name = 'student/detail.html'
    # 设置模型外的数据
    extra_context = {'title': '学生信息详情'}
    # 设置查询模型
    model = StudentInfo
    # 设置上下文对象名称
    context_object_name = 'student'
    # 指定URL中用于获取对象的唯一标识符的参数名称，默认为’pk’。
    # pk_url_kwarg = 'id'


class Create(CreateView):
    # 设置模版文件
    template_name = 'student/create.html'
    # 设置模型外的数据
    extra_context = {'title': '学生信息添加'}
    # 指定form
    form_class = StudentForm
    # 执行成功后跳转地址
    success_url = '/student/list'


class Update(UpdateView):
    # 设置模版文件
    template_name = 'student/update.html'
    # 设置模型外的数据
    extra_context = {'title': '学生信息修改'}
    # 设置查询模型
    model = StudentInfo
    # 指定form
    form_class = StudentForm
    # 执行成功后跳转地址
    success_url = '/student/list'


class Delete(DeleteView):
    # 设置模版文件
    template_name = 'student/delete.html'
    # 设置模型外的数据
    extra_context = {'title': '学生信息删除'}
    # 设置查询模型
    model = StudentInfo
    # 设置上下文对象名称
    context_object_name = 'student'
    # 执行成功后跳转地址
    success_url = '/student/list'





def to_course(request):
    return render(request,'course.html')

def jinja(request):
    # 字符串
    str = "qinshanshan"
    # 时间
    date = datetime.datetime.now()
    # 字典
    myDict = {"tom": "666", "cat": "999", "wzw": "333"}
    # 列表
    myList = ["java", "python", "c"]
    # 元组
    myTuple = ("python", 222, 3.14, False)
    # 对象
    zhangsan = Person("张三",21)
    content_value = {"msg": str, "msg2": myDict, "msg3": myList, "msg4": myTuple, "msg5": zhangsan,"date": date}
    return render(request, 'jinja.html', context=content_value)
















